package com.example.anjia03_3z.service.impl;


import com.example.anjia03_3z.exception.ServiceException;
import com.example.anjia03_3z.mapper.ProductMapper;
import com.example.anjia03_3z.pojo.dto.ProductAddNewDTO;
import com.example.anjia03_3z.pojo.dto.ProductUpdateDTO;
import com.example.anjia03_3z.pojo.entity.Product;
import com.example.anjia03_3z.pojo.vo.ProductListItemVO;
import com.example.anjia03_3z.pojo.vo.ProductStandardVO;
import com.example.anjia03_3z.service.IProductService;
import com.example.anjia03_3z.web.JsonPage;
import com.example.anjia03_3z.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements IProductService {

    @Autowired
    ProductMapper mapper;




    /**
     * 添加新的分类
     *
     * @param productAddNewDTO 获取的数据
     */
    public void addNew(ProductAddNewDTO productAddNewDTO) {
        Product product = new Product();
        BeanUtils.copyProperties(productAddNewDTO,product);
        mapper.insert(product);
    }

    public JsonPage<ProductListItemVO> list(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<ProductListItemVO> list = mapper.list();
        return JsonPage.restPage(new PageInfo<>(list));
    }

    @Override
    public ProductStandardVO getStandard(Long id) {
        ProductStandardVO standardVO = mapper.getStandardById(id);


        if (standardVO == null) {
            String message = "数据已经不存在，请刷新";
            throw new ServiceException(message, ServiceCode.ERR_NOT_FOUND);
        }

        return standardVO;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }


    @Override
    public void updateById(Long id, ProductUpdateDTO productUpdateDTO) {
        ProductStandardVO standardById = mapper.getStandardById(id);
        if (standardById == null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "数据库无该数据");
        }
        Product product = new Product();
        BeanUtils.copyProperties(productUpdateDTO, product);
        int rows = mapper.update(product);
    }

}
